const http = require('http')
const qs = require('querystring')
const config = require('../config')
// const setStorage=require('../Redis/setStorage')
// const UserService=require('../service/UserService')
// const uuidv1=require('uuid/v1')
let limit24coinarrr=[ //市值前24币种
    {symbol:'BTC',data:null},
    {symbol:'ETH',data:null},
    {symbol:'XRP',data:null},
    {symbol:'BCH',data:null},
    {symbol:'EOS',data:null},
    {symbol:'LTC',data:null},
    {symbol:'XLM',data:null},
    {symbol:'ADA',data:null},
    {symbol:'MIOTA',data:null},
    {symbol:'TRX',data:null},
    {symbol:'NEO',data:null},
    {symbol:'USDT',data:null},
    {symbol:'DASH',data:null},
    {symbol:'XMR',data:null},
    {symbol:'XEM',data:null},
    {symbol:'BNB',data:null},
    {symbol:'VEN',data:null},
    {symbol:'ETC',data:null},
    {symbol:'QTUM',data:null},
    {symbol:'OMG',data:null},
    {symbol:'ICX',data:null},
    {symbol:'BCN',data:null},
    {symbol:'ZEC',data:null},
    {symbol:'ONT',data:null}
]
const GetPassword = async (ctx, next) => { //获取用户密码
    let getdata = qs.stringify(ctx.request.body)
    const result = new Promise((resolve, reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: `/yesUser/getUserPassword?${getdata}`,
            method: "GET",
        }
        let req = http.request(opt, (res) => {
            res.setEncoding('utf8')
            let resdata = ''
            res.on('data', (chunk) => {
                resdata += chunk
            })
            res.on('end', () => {
                let data = JSON.parse(resdata)
                // data.data.rate = data.rate
                resolve(data)
            })
        })
        req.on('error', (e) => {
            reject(e)
        })
        // req.write(postdata)
        req.end()
    })
    let data = await result
    if (data.code) {
        ctx.error(data)
    } else {
        ctx.success(data)
    } 
}
const userSignin = async (ctx, next) => { //用户登录
 
    let postdata = JSON.stringify(ctx.request.body)
    const result = new Promise((resolve, reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: '/yesUser/signin',
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            }
        }
        let req = http.request(opt, (res) => {
            res.setEncoding('utf8')
            let resdata = ''

            res.on('data', (chunk) => {
               
                resdata += chunk
            })
          
            res.on('end', () => {
                let data = JSON.parse(resdata)
                           if (data.code == 200) {
                  
                    let userinfo = JSON.parse(data.data)
                    ctx.session.userId = userinfo.userId
                    ctx.session.email = userinfo.email
                    resolve(userinfo)
                }else{
                    resolve(JSON.parse(resdata))
                }
               
            })
        })
        req.on('error', (e) => {
            reject(e)
        })
 
        req.write(postdata)
     
        req.end()
    })
    let data = await result
    if (data.code) {
  
        ctx.error(data)
    } else {
        ctx.success({data})
    }
}
const userRegister = async (ctx, next) => { //用户注册
    let params = ctx.request.body
    params = Object.assign(params, {
        registerIp: String(ctx.ip)
    })
    let postdata = qs.stringify(params)
    const result = new Promise((resolve, reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: `/yesUser/register?${postdata}`,
            method: "PUT",
        }
        let req = http.request(opt, (res) => {
            res.setEncoding('utf8')
            let resdata = ''
            res.on('data', (chunk) => {
                resdata += chunk
            })
            res.on('end', () => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error', (e) => {
            reject(e)
        })
        req.end()
    })
    let data = await result
    if (data.code) {
        ctx.error(data)
    } else {
        ctx.success(data)
    }
}
const usersignout = async (ctx, next) => { //退出登录
    ctx.session = null
    ctx.success(200)
}
const eamilcheck = async (ctx, next) => { //验证邮箱是否存在
    let getdata = qs.stringify(ctx.request.body)
    const result = new Promise((resolve, reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: `/yesUser/check?${getdata}`,
            method: 'GET'
        }
        let req = http.request(opt, (res) => {
            res.setEncoding('utf8')
            let resdata = ''
            res.on('data', (chunk) => {
                resdata += chunk
            })
            res.on('end', () => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error', (e) => {
            reject(e)
        })
        req.end()
    })
    let data = await result
    if (data.code && data.code != 200) {
        ctx.error(data)
    } else {
        ctx.success(data)
    }
}
const ExchangeData = async (ctx, next) => { //查询交易所信息
    let {
        p,
        s
    } = ctx.request.body
    const result = new Promise((resolve, reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: `/yesTop/exchangeList?p=${p}&s=${s}`,
            method: "GET"
        }
        let req = http.request(opt, (res) => {
            res.setEncoding('utf8')
            let resdata = ''
            res.on('data', (chunk) => {
                resdata += chunk
            })
            res.on('end', () => {
                let data = JSON.parse(resdata)
                // data.data.rate = data.rate
                // console.log(data.data.rate)
                resolve(data)
            })
        })
        req.on('error', (e) => {
            reject(e)
        })
        req.end()
    })
    let data = await result
    if (data.code) {
        ctx.error(data)
    } else {
        ctx.success(data)
    }
}
const userselectSelection = async (ctx, next) => {
    //用户分页查询自选
    const userId = ctx.session.userId;
    // console.log(userId)
    // let {p,s}=ctx.request.body
    if (userId) {
        const result = new Promise((resolve, reject) => {
            let opt = {
                hostname: config.hostname,
                port: config.port,
                path: `/yesSelection/select?userId=${userId}`,
                method: "GET"
            };
            let req = http.request(opt, res => {
                res.setEncoding("utf8");
                let resdata = "";
                res.on("data", chunk => {
                    resdata += chunk;
                });
                res.on("end", () => {
                    // console.log(JSON.parse(resdata).data.articles.list)
                    resolve(JSON.parse(resdata));
                });
            });
            req.on("error", e => {
                reject(e);
            });
            req.end();
        });
        let data = await result;
        if (data.code && data.code != 200) {
            ctx.error(data);
        } else {
            ctx.success(data);
        }
    } else {
        let data = {
            code: 200,
            data: null
        };
        ctx.success(data);
    }
};
const usergetarticle = async (ctx, next) => {
    //获取新上线楼层新闻
    const userId = ctx.session.userId
    // console.log(userId)
    if (userId) {
        const result = new Promise((resolve, reject) => {
            let opt = {
                hostname: config.hostname,
                port: config.port,
                path: `/yesTop/userArticles?userId=${userId}`,
                method: "GET"
            };
            let req = http.request(opt, res => {
                res.setEncoding("utf8");
                let resdata = "";
                res.on("data", chunk => {
                    resdata += chunk;
                });
                res.on("end", () => {
                    let responesedata = JSON.parse(resdata);
                    if (responesedata.code == 200) {
                        if (responesedata.data.list.length) {
                            let createdobj = Object.create(null),
                                resultarr = [];
                            responesedata.data.list.forEach((ele, num) => {
                                if (!createdobj[ele.code]) {
                                    createdobj[ele.code] = {
                                        code: ele.code,
                                        flooryesaDescribe: ele.list[0].yesnDescribe,
                                        data: []
                                    };
                                }
                                createdobj[ele.code].data.push(ele);
                            });
                            for (let key in createdobj) {
                                resultarr.push(createdobj[key]);
                            }
                            resolve(resultarr);
                        } else {
                            resolve([]);
                        }
                    } else {
                        resolve([]);
                    }
                });
            });
            req.on("error", e => {
                reject(e);
            });
            req.end();
        });
        let data = await result;
        if (data.code && data.code != 200) {
            ctx.error(data);
        } else {
            let response = {
                code: 200,
                data: data
            }
            ctx.success(response);
        }
    }
};
const huobomarker = async (ctx, next) => {
    //获取火币时时行情
        const result = new Promise((resolve, reject) => {
            let opt = {
                hostname: config.hostname,
                port: config.port,
                path: `/market/price`,
                method: "GET"
            };
            let req = http.request(opt, res => {
                res.setEncoding("utf8");
                let resdata = "";
                res.on("data", chunk => {
                    resdata += chunk;
                });
                res.on("end", () => {
                    let responesedata = JSON.parse(resdata);
                    // limit24coinarrr.forEach((ele,num) => {
                    //     for (let key in responesedata.data) {
                    //         if(ele.symbol==key){
                    //             ele.data=responesedata.data[key][0]
                    //           //  ele.data.extent=parseFloat(Number((responesedata.data.data[key][0].high-responesedata.data.data[key][0].open)/responesedata.data.data[key][0].open*100).toFixed(4))
                    //         }
                    //     }
                    // })
                    resolve(responesedata);
                });
            });
            req.on("error", e => {
                reject(e);
            });
            req.end();
        });
        let data = await result;
        if (data.code && data.code != 200) {
            ctx.error(data);
        } else {
            let response = {
                code: 200,
                data: data
            }
            ctx.success(response);
        }
};
module.exports = {
    userSignin,
    userRegister,
    eamilcheck,
    usersignout,
    ExchangeData,
    GetPassword,
    usergetarticle,
    userselectSelection,
    huobomarker
}